package com.garden.rocketmq.learn.demo.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * 顺序消费者 顺序消费消息
 * Created by Garden on 2020/8/4.
 */
public class OrderConsumer {

    public static void main(String[] args) throws MQClientException {
        //实例化消费者Consumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("order_consumer_group");
        //设置NameServer的地址，Consumer启动后通过NameServer获取目标Topic的路由信息
        consumer.setNamesrvAddr("localhost:9876");
        //订阅消息，可订阅一个或多个Topic以及通过Tag过滤消息
        consumer.subscribe("test_topic","*");
        //设置Consumer实例每次启动都从消息队列头开始消费，默认从上一次消费位置开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        //注册回调实现类来处理从broker拉取回来的消息
        consumer.setMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                consumeOrderlyContext.setAutoCommit(true);
                //处理消息
                for (MessageExt messageExt : list){
                    // 每个队列由唯一线程消费，每个队列（分区）是有序的
                    System.out.println("consumeThread=" + Thread.currentThread().getName()
                            + "queueId=" + messageExt.getQueueId() + ", content:" + new String(messageExt.getBody()));
                    //业务逻辑
                    //...
                }
                // 标记该消息已经被成功消费
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        //启动Consumer实例
        consumer.start();
        System.out.printf("Consumer Started.%n");
    }

}
